package cn.sudatong.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONException;
import org.json.JSONObject;

public class Sudatong {
	private static final String secret = "e9f04d41e1d0ca16731b5b184b2cc575";
	private static final String username = "18605701830@126.com";
	private static Map<String, Map<Integer, String>> phoneMap;
	static {
		phoneMap = new HashMap<String, Map<Integer, String>>();
		Map<Integer, String> mapYidong = new HashMap<Integer, String>();
		mapYidong.put(1, "18");
		mapYidong.put(5, "24");
		mapYidong.put(30, "1124");
		phoneMap.put("移动", mapYidong);
		Map<Integer, String> mapLiantong = new HashMap<Integer, String>();
		mapLiantong.put(1, "1089");
		mapLiantong.put(5, "1093");
		mapLiantong.put(30, "1127");
		phoneMap.put("联通", mapLiantong);
		Map<Integer, String> mapDianxing = new HashMap<Integer, String>();
		mapDianxing.put(10, "1582");
		mapDianxing.put(20, "1583");
		mapDianxing.put(30, "1130");
		phoneMap.put("电信", mapDianxing);

	}

	public static Map sendPost(String url, String param) {
		PrintWriter out = null;
		Map map = new HashMap();
		BufferedReader in = null;
		// String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数

			out.write(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			InputStream inputstream = conn.getInputStream();
			Document doc = null;
			try {
				doc = new SAXReader().read(inputstream);
				doc.setXMLEncoding("utf-8");
			} catch (DocumentException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} // xml保存文件
			Element fields = doc.getRootElement();
			List<Element> elements = fields.elements();
			for (Element e : elements) {
				map.put(e.getName(), e.getText());

			}
			// int first = inputstream.read();
			// byte bytes[] = new byte[inputstream.available()];
			// inputstream.read(bytes);
			// byte bytes1[] = new byte[bytes.length + 1];
			// for (int i = 0; i < bytes1.length; i++) {
			// if (i == 0)
			// bytes1[i] = (byte) first;
			// else
			// bytes1[i] = bytes[i - 1];
			// }
			//
			// try {
			// result = new String(bytes1, "UTF-8");
			// } catch (UnsupportedEncodingException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// return null;
			// }
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return map;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws JSONException {
		// // TODO Auto-generated method stub
		// JSONObject obj=new JSONObject();
		// try{
		// obj.put("userId","f39d2d2a41fd4d920141fd8b270f0002");
		// obj.put("addNum", 250);
		// obj.put("type", "1");
		// obj.put("isErr", 0);
		// obj.put("version", "1.7");
		// }catch (Exception e) {
		// // TODO: handle exception
		// }
		//
		// String power = "16";
		// long timestamp = (new Date()).getTime() / 1000;
		// String url = "http://api.chongzhi.com";
		// // String
		// //
		// addStr="/api/product?power=16&timestamp="+timestamp+"&username=18605701830@126.com&ver=3";
		// String addStr = "/api/sys_phone?phone=15251899255&timestamp="
		// + timestamp + "&username=18605701830@126.com&ver=3";
		//
		// String sign = null;
		// // String
		// //
		// addStr1="power=16&timestamp="+timestamp+"&username=18605701830@126.com&ver=3";
		// String addStr1 = "phone=15251899255&timestamp=" + timestamp
		// + "&username=18605701830@126.com&ver=3";
		// try {
		// String str = URLEncoder.encode(addStr, "UTF-8");
		// sign = "&sign=" + MD5(str);
		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// String str = addStr1 + sign;
		// System.out.print(Sudatong.sendPost(url + "/api/sys_phone", str));
		// System.out.print(recharge1(1,"111111111"));
		String orderId = Sudatong.getOrderId();
		System.out.print(rechargeHuafei(20,"18015895811",orderId));
	}

	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static int rechargeQbi(int count, String to,String orderId) {
		long timestamp = (new Date()).getTime() / 1000;
		String url = "http://api.chongzhi.com";
		String signKey = null;
		String addStr1 = "count=" + count + "&orderid=" + orderId
				+ "&productid=1&timestamp=" + timestamp + "&to=" + to
				+ "&username=" + username + "&ver=3";
		String addStr = "/api/recharge?" + addStr1 + "&";
		try {
			String str = URLEncoder.encode(addStr + secret, "UTF-8");
			signKey = "&signkey=" + MD5(str);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = addStr1 + signKey;
		Map map = Sudatong.sendPost(url + "/api/recharge", str);

		return Integer.parseInt((String) map.get("status"));
	}

	public static int status(String orderId) {
		long timestamp = (new Date()).getTime() / 1000;
		String url = "http://api.chongzhi.com";
		String sign = null;
		String addStr1 = "orderid=" + orderId + "&timestamp=" + timestamp
				+ "&username=" + username + "&ver=3";
		String addStr = "/api/status?" + addStr1;
		try {
			String str = URLEncoder.encode(addStr, "UTF-8");
			sign = "&sign=" + MD5(str);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = addStr1 + sign;
		Map map = Sudatong.sendPost(url + "/api/status", str);

		return Integer.parseInt((String) map.get("status"));
	}

	public static String recharge1(int count, String to) {
		long timestamp = (new Date()).getTime() / 1000;
		String url = "http://api.chongzhi.com";
		String orderId = getOrderId();
		String signKey = null;
		String addStr1 = "count=" + count + "&orderid=" + orderId
				+ "&productid=1&timestamp=" + timestamp + "&to=" + to
				+ "&username=" + username + "&ver=3";
		String addStr = "/api/recharge?" + addStr1 + "&";
		try {
			String str = URLEncoder.encode(addStr + secret, "UTF-8");
			signKey = "&signkey=" + MD5(str);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = addStr1 + signKey;
		return (Sudatong.sendPost(url + "/api/recharge", str)).toString();
	}

	public static String getOrderId() {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
		return sdf.format(calendar.getTime());

	}

	public static String sys_phone(String number) {
		long timestamp = (new Date()).getTime() / 1000;
		String url = "http://api.chongzhi.com";
		String sign = null;
		String addStr1 = "phone=" + number + "&timestamp=" + timestamp
				+ "&username=18605701830@126.com&ver=3";
		String addStr = "/api/sys_phone?" + addStr1;
		try {
			String str = URLEncoder.encode(addStr, "UTF-8");
			sign = "&sign=" + MD5(str);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = addStr1 + sign;
		Map map = Sudatong.sendPost(url + "/api/sys_phone", str);
		String type = (String) map.get("type");
		if (type.contains("移动"))
			return "移动";
		if (type.contains("联通"))
			return "联通";
		if (type.contains("电信"))
			return "电信";
		return null;
	}

	public static int rechargeHuafei(int money, String to,String orderId) {
		long timestamp = (new Date()).getTime() / 1000;
		int count = 0;
		String productid = null;
		String type = sys_phone(to);
		if (money == 1 || money == 30) {
			productid = phoneMap.get(sys_phone(to)).get(money);
			count = 1;
		} else {
			if (type.contains("电信")) {
				productid = phoneMap.get(sys_phone(to)).get(money);
				count = 1;
			} else if (type.contains("移动") || type.contains("联通")) {
				productid = phoneMap.get(sys_phone(to)).get(5);
				count = money / 5;
			}
		}
		if (productid == null)
			return -10;
		String url = "http://api.chongzhi.com";
		String signKey = null;
		String addStr1 = "count=" + count + "&orderid=" + orderId
				+ "&productid=" + productid + "&timestamp=" + timestamp
				+ "&to=" + to + "&username=" + username + "&ver=3";
		String addStr = "/api/recharge?" + addStr1 + "&";
		try {
			String str = URLEncoder.encode(addStr + secret, "UTF-8");
			signKey = "&signkey=" + MD5(str);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = addStr1 + signKey;
		Map map = Sudatong.sendPost(url + "/api/recharge", str);

		return Integer.parseInt((String) map.get("status"));
	}
}
